package com.ikangtai.shecare.common.baseView.articleList;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.CollectedArticle;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncCollectedArticle;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncCollectedArticleMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.FileUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.knowledge.ArticleActivity;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class ArticleAdapter extends BaseAdapter {

    private List<ArticleBean> articleBeanList;
    private LayoutInflater layoutInflater;
    private DateUtil dateUtil = new DateUtil();
    private static final int RESP_OK = 1;
    private static final int RESP_NOK = 2;
    private ArticleBean articleBean = new ArticleBean();
    private DBManager dbManager;
    private CollectedArticle collectedArticle = new CollectedArticle();
    private Context context;
    private int IS_DELETED = 1;
    private int IS_UNDELETED = 0;
    boolean isCollectionView = false;

    public ArticleAdapter(Context context, List<ArticleBean> articleBeanList) {
        this.articleBeanList = articleBeanList;
        this.layoutInflater = LayoutInflater.from(context);
        this.context = context;
        EventBus.getDefault().register(this);
    }

    public ArticleAdapter(Context context, List<ArticleBean> articleBeanList, boolean isCollectionView) {
        this.articleBeanList = articleBeanList;
        this.layoutInflater = LayoutInflater.from(context);
        this.context = context;
        this.isCollectionView = isCollectionView;
        EventBus.getDefault().register(this);
    }

    @Override
    public int getCount() {
        return articleBeanList != null ? articleBeanList.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return articleBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return articleBeanList.get(position).getArticleId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder = null;

        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = layoutInflater.inflate(R.layout.fragment_home_article_item_layout, null);
            viewHolder.articleImageView = (ImageView) convertView.findViewById(R.id.articleImageView);
            viewHolder.articleTitleTextView = (TextView) convertView.findViewById(R.id.articleTitleTextView);
            viewHolder.articleDateTextView = (TextView) convertView.findViewById(R.id.articleDateTextView);
            viewHolder.articleReadTextView = (TextView) convertView.findViewById(R.id.articleReadTextView);
            viewHolder.isCollectedImageBtn = (ImageButton) convertView.findViewById(R.id.isCollectedImageBtn);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        String articleImageUrl = articleBeanList.get(position).getImageUrl();
        Context context = parent.getContext();
        AppLog.i("articleImageUrl = " + articleImageUrl);
        Glide.with(context).load(articleImageUrl)
                .placeholder(R.drawable.article_img_default) // will be displayed before downloaded image
                .error(R.drawable.article_img_default) // will be displayed if the image cannot be loaded
                .into(viewHolder.articleImageView);

        if (isCollectionView) {
            viewHolder.isCollectedImageBtn.setVisibility(View.GONE);
        }

        viewHolder.articleTitleTextView.setText(articleBeanList.get(position).getTitle());
        viewHolder.articleDateTextView.setText(articleBeanList.get(position).getDate());
        viewHolder.isCollectedImageBtn.setSelected(articleBeanList.get(position).isCollected());
        viewHolder.articleReadTextView.setText(""+articleBeanList.get(position).getRead());

        viewHolder.articleImageView.setTag(String.valueOf(getItemId(position)));
        viewHolder.articleImageView.setOnClickListener(new ArticleClickListener());

        viewHolder.articleTitleTextView.setTag(String.valueOf(getItemId(position)));
        viewHolder.articleTitleTextView.setOnClickListener(new ArticleClickListener());

        viewHolder.isCollectedImageBtn.setTag(String.valueOf(position));
        viewHolder.isCollectedImageBtn.setOnClickListener(new ArticleCollectClickListener());

        return convertView;
    }

    class ViewHolder {
        ImageView articleImageView;
        TextView articleTitleTextView;
        TextView articleDateTextView;
        TextView articleReadTextView;
        ImageButton isCollectedImageBtn;
    }

    class ArticleClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            RelativeLayout relativeLayout = (RelativeLayout) v.getParent();
            LinearLayout linearLayout = (LinearLayout) relativeLayout.getChildAt(3);
            TextView textView = (TextView) linearLayout.getChildAt(2);
            textView.setText(""+(Integer.parseInt(textView.getText().toString())+1));
            AppLog.i("you clicked read num = " + textView.getText());

            String articleId = (String) v.getTag();
            Intent intent = new Intent(v.getContext(), ArticleActivity.class);
            intent.putExtra("articleId", App.status + "_" + articleId);
            AppLog.i("Adapter articleId = " + articleId);
            v.getContext().startActivity(intent);
        }
    }

    /**
     * 收藏文章
     */
    class ArticleCollectClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            AppLog.i("Adapter on click collection.");
            String position = (String) v.getTag();
            ArticleBean dataSourceArticleBean = articleBeanList.get(Integer.valueOf(position));
            String articleId = "" + dataSourceArticleBean.getArticleId();
            String title = dataSourceArticleBean.getTitle();
            dataSourceArticleBean.setIsCollected(!articleBean.isCollected());

            if (InternetUtil.hasInternet()) {
                SyncCollectedArticleMsg syncCollectedArticleMsg = new SyncCollectedArticleMsg();
                syncCollectedArticleMsg.setV(v);
                syncCollectedArticleMsg.setPosition(position);
                syncCollectedArticleMsg.setArticleId(articleId);
                syncCollectedArticleMsg.setTitle(title);

                SyncCollectedArticle syncCollectedArticle = new SyncCollectedArticle(v.getContext(), syncCollectedArticleMsg);
                syncCollectedArticle.syncCollectionWithNetwork();
            } else {
                int isDelete;
                prepareDatabase(v);
                if (v.isSelected()) {
                    v.setSelected(false);
                    isDelete = IS_DELETED;
                } else {
                    v.setSelected(true);
                    isDelete = IS_UNDELETED;
                }
                String collectionID = UUID.randomUUID().toString();
                collectedArticle.collectionID = collectionID;
                collectedArticle.collectionName = title;
                collectedArticle.collectionURL = articleId;
                collectedArticle.collectionFrom = 1;
                collectedArticle.collectionDate = dateUtil.getDate();
                collectedArticle.collectionDelete = isDelete;

                articleBean = dataSourceArticleBean;
                sendNOKResp();
                Toast.makeText(context, R.string.network_anomalies_wait, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Subcriber
    private void syncCollectedArticle(SyncCollectedArticleMsg syncCollectedArticleMsg) {
        View v = syncCollectedArticleMsg.getV();
        String position = syncCollectedArticleMsg.getPosition();
        String articleId = syncCollectedArticleMsg.getArticleId();
        String title = syncCollectedArticleMsg.getTitle();

        collectedArticle(v, position, articleId, title);
    }

    private void collectedArticle(View v, String position, final String articleId, final String title) {

        prepareDatabase(v);

        if (v.isSelected()) {
            v.setSelected(false);
            sendHttpPostAddCollection(position, articleId, App.authToken, IS_DELETED, title);
        } else {
            v.setSelected(true);
            sendHttpPostAddCollection(position, articleId, App.authToken, IS_UNDELETED, title);
        }
    }

    private void prepareDatabase(View v) {
        if (dbManager == null)
            dbManager = new DBManager(v.getContext());
    }

    /**
     * post isDelete = 0 收藏；isDelete = 1 取消收藏。
     *
     * @param articleId
     * @param authToken
     * @param isDelete
     * @param title
     */
    private void sendHttpPostAddCollection(final String position, final String articleId, String authToken, final int isDelete, final String title) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this.context);
        String appendUrl = "collection/addCollection.json";
        try {
            JSONArray articleBeanJsonArray = new JSONArray();
            JSONObject articleBeanJSONObject = new JSONObject();
            String collectionID = UUID.randomUUID().toString();
            articleBeanJSONObject.put("collectionID", collectionID);
            articleBeanJSONObject.put("collectionName", title);
            articleBeanJSONObject.put("collectionURL", articleId);
            articleBeanJSONObject.put("collectionFrom", 1);
            articleBeanJSONObject.put("collectionDate", dateUtil.getDate());
            articleBeanJSONObject.put("collectionDelete", isDelete);
            articleBeanJsonArray.put(articleBeanJSONObject);

            collectedArticle.collectionID = collectionID;
            collectedArticle.collectionName = title;
            collectedArticle.collectionURL = articleId;
            collectedArticle.collectionFrom = 1;
            collectedArticle.collectionDate = dateUtil.getDate();
            collectedArticle.collectionDelete = isDelete;

            okHttpClient.add("authToken", authToken);
            okHttpClient.add("collections", articleBeanJsonArray);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    sendNOKResp();
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        if (App.HTTP_RESP_OK == respCode) {
                            articleBean.setRespCode(RESP_OK);
                            articleBean.setArticleId(Integer.valueOf(articleId));
                            articleBean.setPosition(position);
                            sendOKResp(articleBean);
                            AppLog.i("collection onResponse success!");
                        } else {
                            sendNOKResp();
                            AppLog.i("collection onResponse respCode failed! is:" + respCode);
                        }
                    } catch (JSONException e) {
                        sendNOKResp();
                        AppLog.i("collection onResponse failed! is = " + e);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            sendNOKResp();
            e.printStackTrace();
        }
    }

    private void sendNOKResp() {
        articleBean.setRespCode(RESP_NOK);
        EventBus.getDefault().post(articleBean);
    }

    private void sendOKResp(ArticleBean articleBean) {
        EventBus.getDefault().post(articleBean);
    }

    @Subcriber
    private void handleMyInfo(ArticleBean articleBean) {
        switch (articleBean.getRespCode()) {
            case RESP_OK:
                //添加到本地sqlite数据库
                AppLog.i("save collected article data in local sqlite database, and DB_SYNCED!");
                dbManager.addOrDelete(collectedArticle, App.DB_SYNCED);
                //保存收藏的文章图片到本地，或者删除取消收藏的本地图片
                break;
            case RESP_NOK:
                //网络请求失败，仍然添加到本地sqlite数据库
                AppLog.i("save collected article data in local sqlite database, but DB_NOT_SYNCED!");
                dbManager.addOrDelete(collectedArticle, App.DB_NOT_SYNCED);
                break;
        }

        handleCollectedImage(articleBean);
        setPrefArticleCollection(articleBean);
    }

    private void handleCollectedImage(ArticleBean articleBean) {
        AppLog.i("handleCollectedImage! articleId = " + articleBean.getArticleId());
        if (collectedArticle.collectionDelete == IS_UNDELETED)
            saveCollectedImage2Cache(articleBean);
        else
            deleteCollectedImageFromCache(articleBean);
    }

    private void setPrefArticleCollection(ArticleBean articleBean){
        String position = articleBean.getPosition();

        if (collectedArticle.collectionDelete == IS_UNDELETED)
            App.savePreference("article" + position + "_isCollected", true);
        else
            App.savePreference("article" + position + "_isCollected", false);
    }

    private void saveCollectedImage2Cache(ArticleBean articleBean) {
        String originalFileName = "article" + articleBean.getPosition() + ".jpg";
        String externalCacheDir = context.getExternalCacheDir().getAbsolutePath() + "/";
        String originalCacheImagePath = externalCacheDir + originalFileName;

        String collectedFileName = "collectedArticle" + articleBean.getArticleId() + ".jpg";
        String collectedImagePath = externalCacheDir + collectedFileName;
        AppLog.i("saveCollectedImage2Cache, fileName = " + collectedFileName);

        FileUtil.copyFile(originalCacheImagePath, collectedImagePath);
    }

    private void deleteCollectedImageFromCache(ArticleBean articleBean) {
        String fileName = "collectedArticle" + articleBean.getArticleId() + ".jpg";
        String externalCacheDir = context.getExternalCacheDir().getAbsolutePath() + "/";
        String collectedImagePath = externalCacheDir + fileName;
        AppLog.i("deleteCollectedImageFromCache, fileName = " + fileName);

        FileUtil.deleteFile(collectedImagePath);
    }

}
